package com.relax.mybatis.encrypt.algorithm;

import org.bouncycastle.crypto.digests.SM3Digest;

import com.relax.mybatis.constant.EncryptConstants;
import com.relax.mybatis.encrypt.util.BouncyCastleRegister;

/**
 * @author relax
 * @date 2022/07/05
 * @desc SM3加密
 */
public class SM3 {

    public static String encryptToBase64(String data) {
        return Base64.encodeToString(encrypt(data.getBytes(EncryptConstants.DEFAULT_CHARSET)));
    }

    public static String encryptToHex(String data) {
        return Hex.encodeToString(encrypt(data.getBytes(EncryptConstants.DEFAULT_CHARSET)));
    }

    public static byte[] encrypt(byte[] data) {
        SM3Digest sM3Digest = new SM3Digest();
        sM3Digest.update(data, 0, data.length);
        byte[] bytes = new byte[sM3Digest.getDigestSize()];
        sM3Digest.doFinal(bytes, 0);
        return bytes;
    }

    static {
        BouncyCastleRegister.register();
    }
}
